package 职责链.Demo1;

//类似链表的形式
abstract class Handler {
    protected Handler successor = null;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public abstract void handle();
}

class HandlerA extends Handler {

    @Override
    public void handle() {
        boolean handled = false;
        // 业务逻辑
        System.out.println("handlerA");
        //handled表示还需要给下一个handle处理吗
        if(!handled && this.successor != null) {
            this.successor.handle();
        }
    }
}

class HandlerB extends Handler {

    @Override
    public void handle() {
        boolean handled = false;
        System.out.println("handlerB");
        //handled表示还需要给下一个handle处理吗
        if(!handled && successor != null) {
            successor.handle();
        }
    }
}

class HandlerChain {
    private Handler head;
    private Handler tail;

    public void addHandler(Handler handler) {
        if(head == null) {
            this.head = handler;
            this.tail = handler;
            return;
        }
        this.tail.setSuccessor(handler);
        this.tail = handler;
    }

    public void handle() {
        if(head != null) {
            head.handle();
        }
    }
}

class Application {
    public static void main(String[] args) {
        HandlerChain chain = new HandlerChain();
        chain.addHandler(new HandlerA());
        chain.addHandler(new HandlerB());
        chain.handle();
    }
}
